<?php

namespace App\Http\Controllers\Admin;

use App\CodeResponse;
use App\Http\Controllers\Controller;
use App\Models\Permissions;
use App\Services\UsersServices;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class PermissionsController extends AdminController
{
    //添加
    public function  add(Request $request){

        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'http_method' => 'required',
        ]);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }

        $validator = Validator::make($request->all(), [
            'name' => 'unique:roles,name',
        ]);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::AUTH_NAME_REGISTERED);
        }
        Permissions::create($request->except('_token','html','level'));
        return $this->success();
    }
    public function update(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|unique:roles,name,' . $request->id . ',id',
            'http_method' => 'required',
        ]);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }
        $putData = $request->except(['_method','_token','html','level']);
        Permissions::where([['id','=', $request->id]])->update($putData);
        return $this->success();

    }
    //列表
    public function list(Request $request){
        // 读取出所有的权限
        $permissionsAll = (new Permissions())->getLevelList();
        return $this->success($permissionsAll);
    }
    //列表
    public function listTree(Request $request){
        // 读取出所有的权限
        $permissionsAll = (new Permissions())->getAllList();
        return $this->success($permissionsAll);
    }

    // 上传
    public function upfile(Request $request) {
        $url = config('filesystems.disks.icon.url');
        $default = config('filesystems.disks.icon.default');
        $pic =  UsersServices::getInstance()->upfile($request,$url,$default,'icon');
        return $this->success([
                'pic'=>$pic,
            ]
        );
    }
    //删除
    public function delete(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required|integer',
        ]);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }
        $permissions = new Permissions();
        $arr = $permissions->getSubTreeIdArr($request->id);

        array_push($arr,$request->id);

        $permissions->destroy($arr);
        return $this->success();
    }




}
